#include "stack.h"
#include <stdlib.h>

void stack_init(Stack** s) {

	*s = (Stack*)malloc(sizeof(Stack));
	(*s)->size = 0;
	(*s)->top = NULL;

}

void stack_cleanup(Stack* s) {

	while(stack_size(s) != 0)
		stack_pop(s);

	free(s);

}

int stack_size(Stack* s) {

	return s->size;
	
}

void stack_push(Stack* s, void* data) {

	StackElement* element = (StackElement*)malloc(sizeof(StackElement));

	element->data = data;
	element->next = s->top;

	s->top = element;

	s->size++;

}

void* stack_pop(Stack* s) {

	StackElement* temp;
	void* ret;

	if(s->top == NULL)
		return NULL;

	temp = s->top;
	ret = temp->data;

	s->top = temp->next;

	free(temp);

	s->size--;

	return ret;

}

void* stack_peek(Stack* s) {

	if(stack_size(s) == 0)
		return NULL;
	else
		return s->top->data;

}

/* Zamień stos na tablicę wskaźników w elementach */
/* (od pierwszego elementu włożonego na stos do ostatniego) */
void** stack_to_array(Stack* s) {

	int i;

	StackElement* element;
	
	void** ret = malloc(stack_size(s)*sizeof(void*));

	element = s->top;

	for(i=stack_size(s)-1;i>=0;i--) {

		ret[i] = element->data;
		element = element->next;
		
	}
	
	return ret;

}